const Service = require("egg").Service;
const axios = require("axios");

class WxfriendService extends Service {
  async getFriendList(mywxid, field, page, pageSize) {
    const { ctx } = this;
  
    try {
      // 构建查询条件
      let query = { ownerWxid: mywxid };
  
      // 处理查询参数
      if (field.nick) {
        query.nick = new RegExp(field.nick, "i"); // 不区分大小写
      }
      if (field.remark) {
        query.remark = new RegExp(field.remark, "i");
      }
      if (field.phone) {
        query.phone = new RegExp(field.phone);
      }
      if (field.tags && field.tags.length > 0) {
        query.tags = { $in: field.tags };
      }
      if (field.isfriend !== undefined) {
        query.isfriend = field.isfriend;
      }
      if (field.isopenai !== undefined) {
        query.isopenai = field.isopenai;
      }
      if (field.isconfirmpay !== undefined) {
        query.isconfirmpay = field.isconfirmpay;
      }
      if (field.ischat !== undefined) {
        query.ischat = field.ischat;
      }
      if (field.isreceive !== undefined) {
        query.isreceive = field.isreceive;
      }
      if (field.isvip !== undefined) {
        query.isvip = field.isvip;
      }
  
      // 验证排序字段
      const allowedSortFields = ['createTime', 'updateTime'];
      const sortBy = field.sortBy || 'createTime';
      if (!allowedSortFields.includes(sortBy)) {
        throw new Error(`Invalid sort field: ${sortBy}`);
      }
  
      // 计算跳过的文档数量
      const skip = (page - 1) * pageSize;
  
      // 获取总数
      const total = await ctx.model.Wxfriend.countDocuments(query);
  
      // 动态排序 + 分页查询
      const data = await ctx.model.Wxfriend.find(query)
        .skip(skip)
        .limit(pageSize)
        .sort({
          [sortBy]: -1,     // 主排序字段（降序）
          nickBrief: 1      // 次排序字段（升序）
        });
  
      return {
        code: 20000,
        msg: "获取成功",
        data: {
          count: total,
          list: data,
        },
      };
    } catch (error) {
      this.logger.error("获取用户信息失败:", error.message);
      return {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
        data: {
          count: 0,
          list: [],
        },
      };
    }
  }

  async updateFrendList(mywxid) {
    const { ctx } = this;
    await ctx.model.Wxfriend.deleteMany({
      ownerWxid: mywxid,
    });
    try {
      // 调用外部接口获取当前登录微信用户信息
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "getFriendList",
          data: {
            type: "2",
          },
        },
        {
          params: { mywxid }, // 将 wxid 作为 Params 参数传递
        }
      );

      // 好友列表数据
      const datalist = response.data.result;

      await Promise.all(
        datalist.map((friend) =>
          ctx.model.Wxfriend.create({
            ownerWxid: mywxid,
            wxid: friend.wxid || "",
            nick: friend.nick || "",
            wxNum: friend.wxNum || "",
            phone: friend.phone || "",
            remark: friend.remark || "",
            sex: friend.sex || "",
            avatarMinUrl: friend.avatarMinUrl || "",
            avatarMaxUrl: friend.avatarMaxUrl || "",
            nickBrief: friend.nickBrief || "",
            nickWhole: friend.nickWhole || "",
            remarkBrief: friend.remarkBrief || "",
            remarkWhole: friend.remarkWhole || "",
            enBrief: friend.enBrief || "",
            enWhole: friend.enWhole || "",
            v3: friend.v3 || "",
            sign: friend.sign || "",
            country: friend.country || "",
            province: friend.province || "",
            city: friend.city || "",
            label: friend.label || "",
            tags: [],
            isfriend: true,
          })
        )
      );
      return datalist;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取用户信息失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }

  // 修改数据
  async editFriend(mywxid, wxid, field) {
    const { ctx } = this;

    if (!wxid.includes("gh_") && !wxid.includes("chatroom") && !wxid.includes("openim")) {
      try {
        const result = await ctx.model.Wxfriend.findOneAndUpdate(
          { ownerWxid: mywxid, wxid },
          { $set: field },
          { new: true }
        );
        // console.log( result)
        if (!result) {
          console.log("editFriend", mywxid, wxid, field);
          throw new Error("未找到该好友");
        }

        return result;
      } catch (error) {
        this.logger.error("更新好友状态失败:", error);
        throw error;
      }
    }
  }

  async editFriendRemark(mywxid, wxid, field) {
    const { ctx } = this;
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "editObjRemark",
          data: {
            wxid,
            remark: field.remark,
          },
        },
        {
          params: { mywxid }, // 将 wxid 作为 Params 参数传递
        }
      );

      if (response.data.code === 200) {
        const result = await ctx.model.Wxfriend.findOneAndUpdate(
          { ownerWxid: mywxid, wxid },
          { $set: field },
          { new: true }
        );

        if (!result) {
          throw new Error("未找到该好友");
        }

        return result;
      }
    } catch (error) {
      this.logger.error("更新好友状态失败:", error);
      throw error;
    }
  }
  // 批量修改好友字段
  async batchEditFriend() {
    const { ctx, service } = this;
    const { mywxid, wxids, field } = ctx.request.body;

    try {
      // 参数验证
      if (!Array.isArray(wxids) || wxids.length === 0) {
        throw new Error("wxids必须是非空数组");
      }

      if (!field || Object.keys(field).length === 0) {
        throw new Error("field不能为空");
      }

      // 调用service批量更新
      const results = await Promise.all(
        wxids.map((wxid) => service.wxfriend.editFriend(mywxid, wxid, field))
      );
      // 检查响应状态
      return results;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("批量收款失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }
  // 自动化操作一 确认收款
  async confirmTrans(mywxid, wxid, transcationid, transferid) {    
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "confirmTrans",
          data: {
            wxid,
            transcationid,
            transferid,
          },
        },
        {
          params: { wxid: mywxid },
        }
      );

      // 检查响应状态
      return response.data;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("确认收款失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }

  // 删除好友
  async deleteFriend(mywxid, wxid) {
    const { ctx } = this;
    // console.log("删除好友", mywxid, wxid);
    try {
      // 参数验证
      if (!mywxid || !wxid) {
        throw new Error("缺少必要参数");
      }

      // 先调用接口删除微信好友
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "delFriend",
          data: {
            wxid,
          },
        },
        {
          params: { wxid: mywxid },
        }
      );
      console.log("删除好友接口返回数据", response);
      // 如果接口调用成功，再删除数据库记录
      if (response.data.code === 200) {
        const result = await ctx.model.Wxfriend.deleteOne({
          wxid,
          ownerWxid: mywxid,
        });

        if (result.deletedCount === 0) {
          return {
            code: 50000,
            msg: "数据库中未找到该好友记录",
            data: null,
          };
        }

        return true;
      } else {
        throw new Error(response.data.msg || "调用接口删除好友失败");
      }
    } catch (error) {
      this.logger.error("删除好友失败:", error.message);
      return {
        code: 50000,
        msg: error.message || "删除好友失败，请检查网络或接口状态",
        data: null,
      };
    }
  }

  // 同意好友请求
  async agreeFriendReq(mywxid, payload) {
    const { ctx } = this;
    try {
      // 参数验证
      if (!mywxid || !payload.v3 || !payload.v4) {
        throw new Error("缺少必要参数");
      }

      // 1. 调用接口同意好友请求
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "agreeFriendReq",
          data: {
            v3: payload.v3,
            v4: payload.v4,
            scene: payload.scene,
            role: "0",
          },
        },
        {
          params: { wxid: mywxid },
        }
      );

      // 2. 如果同意成功，获取新好友信息并保存到数据库
      if (response.data.code === 200) {
        // 延迟 1 秒等待好友信息同步

        // 保存到数据库
        await ctx.model.Wxfriend.create({
          ownerWxid: mywxid,
          wxid: payload.wxid || "",
          nick: payload.nick || "",
          wxNum: payload.wxNum || "",
          phone: payload.phone || "",
          remark: payload.remark || "",
          sex: payload.sex || "",
          avatarMinUrl: payload.avatarMinUrl || "",
          avatarMaxUrl: payload.avatarMaxUrl || "",
          nickBrief: payload.nickBrief || "",
          nickWhole: payload.nickWhole || "",
          remarkBrief: payload.remarkBrief || "",
          remarkWhole: payload.remarkWhole || "",
          enBrief: payload.enBrief || "",
          enWhole: payload.enWhole || "",
          v3: payload.v3 || "",
          sign: payload.sign || "",
          country: payload.country || "",
          province: payload.province || "",
          city: payload.city || "",
          label: payload.label || "",
          tags: [],
          isfriend: true,
        });

        return true;
      }

      throw new Error(response.data.msg || "同意好友请求失败");
    } catch (error) {
      this.logger.error("同意好友请求失败:", error.message);
      return {
        code: 50000,
        msg: error.message || "操作失败，请检查网络或接口状态",
        data: null,
      };
    }
  }

  // 通过手机号 查询陌生人信息，获取V3
  async queryNewFriend(mywxid, phone) {
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "queryNewFriend",
          data: {
            obj: phone,
          },
        },
        {
          params: { wxid: mywxid },
        }
      );
      // 检查响应状态
      return response.data.result;
    } catch (error) {
      // 捕获异常并返回错误信息
    }
  }

  // 添加好友_通过v3
  async addFriendByV3(mywxid, v3, content) {
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "addFriendByV3",
          data: {
            v3: v3,
            content: content,
            scene: "15",
          },
        },
        {
          params: { wxid: mywxid },
        }
      );
      // 检查响应状态
      return response.data;
    } catch (error) {
      // 捕获异常并返回错误信息
    }
  }

  // 添加好友_通过群wxid
  async addFriendByGroupWxid(mywxid, wxid, gid, content) {
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "addFriendByGroupWxid",
          data: {
            wxid: wxid,
            gid: gid,
            content: content,
            scene: "14",
          },
        },
        {
          params: { wxid: mywxid },
        }
      );
      // 检查响应状态
      return response.data;
    } catch (error) {
      // 捕获异常并返回错误信息
    }
  }
}
module.exports = WxfriendService;
